package itrans;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.*;

public class Controller extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      IOException, ServletException {
    process(request, response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws
      IOException, ServletException {
    process(request, response);
  }

  private void process(HttpServletRequest request, HttpServletResponse response) throws
      IOException, ServletException {

	RequestDispatcher dispatcher;	
	HttpSession session = request.getSession(true);
	
	// Set some session parameters 
	String timeoutstr = getServletContext().getInitParameter("idleTimeout");
	int timeout = Integer.parseInt(timeoutstr);
	session.setMaxInactiveInterval(timeout);
	
	// Get the action to be processed
    String action = request.getParameter("action");
    if (action == null)
		action = "";
	
	// Determine which servlet to forward the request to
    if (action.equals("register")) {
        dispatcher = request.getRequestDispatcher("/Register");
        dispatcher.forward(request, response);
	}
    else if (action.equals("login")) {
        dispatcher = request.getRequestDispatcher("/Login");
		dispatcher.forward(request, response);
	}
	else if (action.equals("save_stops"))
	{
		dispatcher = request.getRequestDispatcher("/SaveStop");
		dispatcher.forward(request, response);
	}
	else if (action.equals("get_stops"))
	{
		dispatcher = request.getRequestDispatcher("/GetStop");
		dispatcher.forward(request, response);
	}
	else if (action.equals("logout")){
		// invalidated the session and return to main page
		session.invalidate(); 
	}
	else if (action.equals("delete_stop"))
	{
		dispatcher = request.getRequestDispatcher("/DeleteStop");
		dispatcher.forward(request, response);
	}
    else {
        dispatcher = request.getRequestDispatcher("/WEB-INF/bad_request.jsp");
        dispatcher.forward(request, response);
    }  
  }

  public void init()
  {
    Connection con;
    int rowsAffected = 0;
    
    // initialize connection pool. Everything is copied I don't know
    // what it is actually doing.
    try {
		DriverAdapterCPDS ds = new DriverAdapterCPDS();
		ds.setDriver(DBUtil.DB_JDBC_DRIVER);
		ds.setUrl(DBUtil.DB_URL);
		ds.setUser(DBUtil.DB_USER);
		ds.setPassword(DBUtil.DB_PWD);

		SharedPoolDataSource dbcp = new SharedPoolDataSource();
		dbcp.setConnectionPoolDataSource(ds); // set the datasource for connection poo
		getServletContext().setAttribute("dbpool",dbcp); // make it available to all servlets
	}
	catch (Exception ex) {
		getServletContext().log("SQLGatewayPool Error: " + ex.getMessage());
	}
	
	// Initialize dynamic databases if the `dbInit` parameter in
	// web.xml is set to "true"
    try {
      String dbInit = getServletContext().getInitParameter("dbInit");
      System.out.println(dbInit);
      
      if (dbInit.equals("true")) {	// dbInit context says to initialize DB
        con = DBUtil.getConnection();
		// Get a statement (used to issue SQL statements to the DB)
		Statement stmt = con.createStatement();
		init_users_table(stmt);
		stmt.close();
		con.close();
      }
    }
    catch(SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public void init_users_table(Statement stmt)
  {
	String query;
	int rowsAffected;
	
	try {
		// drop Users table if it exists
		query = "DROP TABLE Users;";
		rowsAffected = stmt.executeUpdate(query);
		
		// clear out MyStops table 
		query = "DELETE FROM MyStops;";
		rowsAffected = stmt.executeUpdate(query);

		// create users table
		query = "CREATE TABLE Users ("
			  + "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
			  + "username VARCHAR(16) UNIQUE,"
			  + "password VARCHAR(16),"
			  + "first_name VARCHAR(64),"
			  + "last_name VARCHAR(64),"
			  + "email VARCHAR(255) UNIQUE,"
			  + "phone VARCHAR(64));";
		rowsAffected = stmt.executeUpdate(query);

		// add a test account
		query = "INSERT INTO Users "
			  + "(username, password, first_name, last_name, email, phone) "
			  + "VALUES ('testing', '4Testing', 'Tom', 'Tester', "
			  + "'tom@gmail.com', '1-888-555-1212');";
		rowsAffected = stmt.executeUpdate(query);
	}
	catch(SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
